<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderServiceProfile;
use App\Models\ReceiptInfo;
use App\Models\SmsLog;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use zgldh\QiniuStorage\QiniuStorage;

class UserController extends BaseController
{

    /**
     * 上传补充资料
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-04
     * @param Request $request
     * @return void
     */
    public function uploadOrderProfiles(Request $request)
    {
        $rules = [
            'id' => ['required'],
            'customer_data' => ['required'],
            'customer_data_name' => ['required'],
        ];

        $message = [
            'id.required' => '参数错误-id',
            'customer_data.required' => '参数错误-补充资料',
            'customer_data_name.required' => '参数错误-补充资料名称',
        ];

        $payload = $request->only('id', 'customer_data', 'customer_data_name');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $result = OrderServiceProfile::find($payload['id']);
        if (empty($result)) {
            return fail_message('未找到对应资料');
        }

        $result->customer_data = $payload['customer_data'];
        $result->customer_data_name = $payload['customer_data_name'];
        if ($result->save()) {
            return success();
        } else {
            return fail_message();
        }
    }
    /**
     * 获取七牛云token
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-05-14
     * @param Request $request
     * @return void
     */
    public function getQiniuToken()
    {
        $disk = QiniuStorage::disk('qiniu');
        $token = $disk->uploadToken();
        return success(['token' => $token]);
    }

    /**
     * 会员主页
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function userHome(Request $request)
    {
        $user = user();
        // 我的订单统计
        $user->my = UserService::getUserOrderStatistics($user->id);
        // 邮箱账户
        $user->email_account = UserService::getUserOrderEmail($user->id);
        // // 系统注册信息
        // $user->system_account = UserService::getUserOrderSystemRegister($user->id);
        // // 近期订单
        // $user->recent_order = UserService::getUserRecentOrderList($user->id);
        return success($user);
    }

    /**
     * 投稿系统注册信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-05-10
     * @param Request $request
     * @return void
     */
    public function systemAccount(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],

        ];

        $message = [
            'page.required' => '参数错误-页码',
            'limit.required' => '参数错误-条数',
        ];

        $payload = $request->only('page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }


        $data = UserService::getUserOrderSystemRegisterPaginate(userId(), $payload['page'], $payload['limit']);
        // dd($data);
        return successPaginate($data);
    }

    /**
     * 近期订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-05-10
     * @param Request $request
     * @return void
     */
    public function recentOrder(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],

        ];

        $message = [
            'page.required' => '参数错误-页码',
            'limit.required' => '参数错误-条数',
        ];

        $payload = $request->only('page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $data = UserService::getUserRecentOrderListPaginate(userId(), $payload['page'], $payload['limit']);
        // dd($data);
        return successPaginate($data);
    }


    /**
     * 获取会员个人信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function getUserInfo(Request $request)
    {
        $user = user();
        $user->loadCount(['orderAmount']);

        return success($user);
    }


    /**
     * 修改个人信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function modifyUserInfo(Request $request)
    {
        $rules = [
            'realname' => ['required'],
            'surname' => ['required'],
            'name' => ['required'],
            'email' => ['required'],
            'institution' => ['required'],
            'province_id' => ['required'],
            // 'city_id' => ['required'],
            // 'district_id' => ['required'],
            'address'  => ['required'],
        ];

        $message = [
            'realname.required' => '请输入姓名',
            'surname.required' => '请输入称谓',
            'name.required' => '请输入名',
            'email.required' => '请输入邮箱',
            'institution.required' => '请输入机构',
            'province_id.required' => '请输入省',
            // 'city_id.required' => '请输入市',
            // 'district_id.required' => '请输入区',
            'address.required' => '请输入邮寄地址',
        ];

        $payload = $request->only('avatar', 'phone', 'realname', 'wechart', 'wechart_name', 'surname', 'name', 'email', 'address', 'province_id', 'city_id', 'district_id', 'zip_code', 'institution', 'institution_detail');

        //, 'password'
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        // 创建用户
        $result = User::where('id', userId())->update($payload);

        if ($result) {
            return success_message('成功');
        } else {
            return fail_message('失败');
        }
    }


    /**
     * 检验验证码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-13
     * @param Request $request
     * @return void
     */
    public function checkMessageCode(Request $request)
    {
        $rules = [
            'phone' => ['required'],
            'code' => ['required'],
        ];

        $message = [
            'phone.required' => '请输入手机号',
            'code.required' => '请输入验证码',
        ];

        $payload = $request->only('phone', 'code');

        //, 'password'
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $verify_code = SmsLog::check_code($payload['code'], $payload['phone']);

        if (empty($verify_code)) {
            return fail_message('验证码不正确');
        }

        return success();
    }


    /**
     * 修改个人手机号码 @todo Something
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-14
     * @param Request $request
     * @return void
     */
    public function modifyUserPhone(Request $request)
    {
        $rules = [
            'phone' => ['required'],
            'code' => ['required'],
        ];

        $message = [
            'phone.required' => '请输入手机号',
            'code.required' => '请输入验证码',
        ];

        $payload = $request->only('phone', 'code');

        //, 'password'
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $verify_code = SmsLog::check_code($payload['code'], $payload['phone']);

        if (empty($verify_code)) {
            return fail_message('验证码不正确');
        }

        $result = UserService::modifyUserPhone(user(), $payload);
        if ($result) {
            return success_message('修改成功');
        } else {
            return fail_message('修改失败');
        }
    }


    /**
     * 修改密码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function modifyPassword(Request $request)
    {
        $rules = [
            'old_password' => ['required'],
            'password' => ['required'],
            'confirm_password' => ['required', 'same:password'],

        ];

        $message = [
            'old_password.required' => '请输入原始密码',
            'password.required' => '请输入新密码',
            'confirm_password.required' => '请输入确认密码',
            'confirm_password.same' => '两次密码不一致',
        ];

        $payload = $request->only('old_password', 'password', 'confirm_password');

        //, 'password'
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $user = user();
        if (User::where('username', $user['username'])->doesntExist()) {
            return fail_message('请先注册用户');
        }

        if (!$token = auth('api')->attempt(['username' => $user['username'], 'password' => $payload['old_password']])) {
            return fail([], '旧密码错误', 401);
        }

        $user->password = bcrypt($payload['confirm_password']);
        if ($user->save()) {
            auth('api')->logout();
            return success();
        } else {
            return fail_message();
        }
    }


    /**
     * 获取用户服务订单列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @return void
     */
    public function getUserOrderList(Request $request)
    {
        $payload = $request->only('order_status', 'datetime');
        $list = UserService::getUserOrderList(userId(), $payload, ['id', 'order_sn', 'order_amount', 'service', 'order_status', 'created_at', 'is_eval']);
        return successPaginate($list);
    }


    /**
     * 获取订单详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function getOrderDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $detail = UserService::getOrderDetail($payload['id']);
        return success($detail);
    }


    /**
     * 取消订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function cancellationOrder(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $detail = UserService::modifyOrderStatus($payload['id'], -1);
        return success($detail);
    }



    /**
     * 评价订单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function evaluateOrder(Request $request)
    {
        $rules = [
            'order_id' => ['required'],
            // 'journal_name' => ['required'],
            // 'journal_area' => ['required'],
            // 'title' => ['required'],
            // 'title_href' => ['required'],
            // 'cover_page' => ['required'],
            'content' => ['required'],

        ];

        $message = [
            'order_id.required' => '缺少参数订单id',
            // 'journal_name.required' => '请输入文章发表期刊名称',
            // 'journal_area.required' => '请输入期刊分区',
            // 'title.required' => '请输入文章标题',
            // 'title_href.required' => '请输入文章发表后标题链接',
            // 'cover_page.required' => '请输入展示封面图',
            'content.required' => '请输入评价内容',
        ];

        $payload = $request->only('order_id', 'journal_name', 'journal_area', 'title', 'title_href', 'cover_page', 'content');

        //, 'password'
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $result = UserService::evaluateOrder(user(), $payload);
        if ($result) {
            return success_message('评论成功');
        } else {
            return fail_message('评论失败');
        }
    }


    /**
     * 验收订单（完成订单）
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-03-12
     * @param Request $request
     * @return void
     */
    public function acceptOrder(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $detail = UserService::modifyOrderStatus($payload['id'], 2);
        return success($detail);
    }

    /**
     * 添加或者编辑发票信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-03
     * @param Request $request
     * @return void
     */
    public function updateOrCreateReceiptInfo(Request $request)
    {
        $rules = [
            // 'id' => ['required'],
            'type' => ['required'],
            'header' => ['required'],
            // 'receive_user' => ['required'],
            // 'receive_mobile' => ['required'],
            // 'receive_addr' => ['required'],
            'tax_user_id' => ['required'],

        ];

        $message = [
            // 'id.required' => '缺少参数',
            'type.required' => '未选择发票类型',
            'header.required' => '请填写发票抬头',
            // 'receive_user.required' => '请填写收件人姓名',
            // 'receive_mobile.required' => '请填写电话号码',
            // 'receive_addr.required' => '请填写详细地址',
            'tax_user_id.required' => '请填写纳税人识别号/统一社会信用代码',
        ];

        $payload = $request->only('id', 'type', 'header', 'receive_user', 'receive_mobile', 'receive_addr', 'tax_user_id', 'company_addr', 'company_phone', 'bank_name', 'bank_number', 'tax_type', 'tax_cert', 'remark');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $payload['user_id'] = userId();

        $id = $payload['id'];

        unset($payload['id']);
        // dd($payload);

        if (isset($id) && $id != '') {
            $result = ReceiptInfo::updatReceipt($payload, $id);
            // $result = Medical::where('id',$id)->update($payload);
        } else {
            $result = ReceiptInfo::create($payload);
        }
        if ($result) {
            return success();
        } else {
            return fail_message();
        }
    }

    /**
     * 发票信息列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function receiptInfoList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '缺少参数-页码',
            'limit.required' => '缺少参数-限制条数',
        ];

        $payload = $request->only('page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $data = UserService::getRectiptInfoListPaginate(userId(), $payload['page'], $payload['limit']);

        return successPaginate($data);
    }

    /**
     * 发票信息详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function receiptInfoDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $detail = ReceiptInfo::where('id', $payload['id'])->select('*', 'type as type_text', 'tax_type as tax_type_text')->first();
        return success($detail);
    }

    /**
     * 删除发票信息详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function receiptInfoDelete(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $detail = ReceiptInfo::where('id', $payload['id'])->delete();
        return success($detail);
    }


    /**
     * 设置默认开票信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function receiptInfoSetDefault(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $info = ReceiptInfo::setDefaultReceiptInfo($payload['id']);
        return success($info);
    }

    /**
     * 申请发票前
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function checkReceipt()
    {
        return success(UserService::getReceiptInfo(userId()));
    }


    /**
     * 申请开票（提交）
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function applyReceipt(Request $request)
    {
        $rules = [
            'order_id' => ['required'],
            'receipt_info_id' => ['required'],
            'total_money' => ['required'],
        ];

        $message = [
            'order_id.required' => '缺少参数-开票订单',
            'receipt_info_id.required' => '缺少参数-发票信息',
            'total_money.required' => '缺少参数-开票金额',
        ];

        $payload = $request->only('order_id', 'receipt_info_id', 'total_money');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        return success(UserService::applyReceipt($payload, userId()));
    }

    /**
     * 发票记录列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @param Request $request
     * @return void
     */
    public function receiptList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '缺少参数-页码',
            'limit.required' => '缺少参数-限制条数',
        ];

        $payload = $request->only('page', 'limit', 'datetime');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $data = UserService::getReceiptList(userId(), $payload['page'], $payload['limit']);

        return successPaginate($data);
    }

    /**
     * 可开票金额
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-05
     * @return void
     */
    public function receiptAmount()
    {
        return success(['amount' => Order::where(['user_id' => userId(), 'order_status' => 2])->sum('pay_amount')]);
    }

    /**
     * 获取发票详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-07
     * @param Request $request
     * @return void
     */
    public function getReceiptDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数-页码',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        return success(UserService::getReceiptDetail($payload['id']));
    }

    /**
     * 评价列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-13
     * @param Request $request
     * @return void
     */
    public function getEvalList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '缺少参数-页码',
            'limit.required' => '缺少参数-限制条数',
        ];

        $payload = $request->only('page', 'limit', 'order_status', 'created_at');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $data = UserService::getEvalList(userId(), $payload);

        return successPaginate($data);
    }
}
